<template>
  <div>
    <div>
      <div class="handle-box">
        <div>
          <el-input
            v-model="searchfrom.queryImei"
            placeholder="请输入设备编号/内容"
            class="handle-input mr10"
          ></el-input>
        </div>
        <div>
          <!-- <span class="title_name">设备类型： </span> -->
          <el-select
            v-model="searchfrom.queryDevType"
            placeholder="全部类型"
            class="handle-select mr10"
            style="width: 300px"
            @change="handlequeryDevType"
          >
            <el-option
              v-for="item in devTypeList"
              :key="item.devTypeId"
              :label="item.devTypeName + '(' + item.option + ')'"
              :value="item.devTypeId"
            ></el-option>
          </el-select>
        </div>

        <!--报警状态  -->
        <div>
          <!-- <span class="title_name"> 报警处理状态：</span> -->
          <el-select
            v-model="searchfrom.queryCheckState"
            placeholder="全部状态"
            class="handle-select mr10"
          >
            <el-option
              v-for="item in alarmdisposeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </div>
        <div>
          <!-- <span class="title_name">报警时间：</span> -->
          <el-date-picker
            v-model="alarm_time"
            type="datetimerange"
            range-separator="至"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changeAlarm_time"
            :default-time="defaultTime"
          >
          </el-date-picker>
        </div>
        <el-button
          type="primary"
          class="icon-search"
          icon="el-icon-search"
          @click="handleSearch"
          >搜索</el-button
        >
        <el-button class="icon-search" @click="emptySearch">清空</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @select="handleSelectionChange"
        @select-all="selectAllchange"
      >
        <el-table-column prop="id" label="序列号" width="65" align="center">
          <template #default="scope">
            {{
              Number(
                searchfrom.pageSize * (searchfrom.pageNum - 1) +
                  1 +
                  scope.$index
              )
            }}
          </template>
        </el-table-column>
        <el-table-column prop="alarmTypeName" label="报警类型">
        </el-table-column>
        <el-table-column prop="imei" label="设备号"></el-table-column>
        <el-table-column prop="alarmState" label="状态">
          <template #default="scope">
            <div v-if="scope.row.checkState == 0">待处理</div>
            <div v-else-if="scope.row.checkState == 1">处理中</div>
            <div v-if="scope.row.checkState == 2">已处理</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              v-if="scope.row.checkState != 2 && is_look_dealpolice"
              type="text"
              @click="handledispose(2, scope.row)"
              >处理</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="searchfrom.pageNum"
          :page-size="searchfrom.pageSize"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <!-- 处理完成弹窗 -->
    <el-dialog
      title="确认处理"
      :close-on-click-modal="false"
      @close="handleclose"
      v-model="finshVisible"
      width="30%"
    >
      <el-form label-width="120px">
        <el-form-item label="处理描述">
          <el-input
            class="remarkValue"
            v-model="shaving.operateDescb"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-upload
            action=""
            name="file"
            accept=".png,.jpg,.gif"
            list-type="picture-card"
            limit="3"
            :on-preview="handlePictureCardPreview"
            :http-request="uploadFile"
            :before-remove="beforeremoveElse"
            ref="uploadc"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="finshVisible = false">取 消</el-button>
          <el-button type="primary" @click="HandlerSuccess">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 派人 -->
    <el-dialog
      title="派人"
      v-model="editVisible"
      :close-on-click-modal="false"
      @close="handleclose"
      width="40%"
    >
      <el-form label-width="120px">
        <el-form-item label="派人">
          <el-select
            v-model="personnel"
            placeholder="请选择"
            class="handle-input1 mr10"
          >
            <el-option
              v-for="item in personnelList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveEditDispose">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 初始化设备报警类型 -->
    <el-dialog title="设备XS5asd84" v-model="dev_detailShow" width="25%">
      <div>
        <span>设备编号：{{ dev_detail.imei }}</span
        ><span class="marginleft20"
          >设备类型：{{ dev_detail.devTypeName }}</span
        >
      </div>
      <div class="margin20">
        <el-button type="danger">待处理</el-button>
        <span class="marginleft20" style="color: #f64c6a">{{
          dev_detail.alarmTypeName
        }}</span>
      </div>
      <div class="exportbtn">
        <el-descriptions title="" :column="1" border>
          <el-descriptions-item label="温度/℃">{{
            (obj_airSwitch.temp || 0 * 0.1).toFixed(1)
          }}</el-descriptions-item>
          <el-descriptions-item label="总有功电量/KW.H">{{
            (obj_airSwitch.epTotal || 0 * 0.1).toFixed(1)
          }}</el-descriptions-item>
          <el-descriptions-item label="总无功电量/KW.H">{{
            (obj_airSwitch.eqTotal || 0 * 0.1).toFixed(1)
          }}</el-descriptions-item>
          <!-- <el-descriptions-item
            label="剩余电量/KW.H"
            >{{
              (obj_airSwitch.eresidual * 0.1).toFixed(1)
            }}</el-descriptions-item
          >
          <el-descriptions-item
            label="漏电值/mA"
            v-if="obj_airSwitch.iresidual"
            >{{ obj_airSwitch.iresidual }}</el-descriptions-item
          > -->
          <el-descriptions-item label="电流有效值/A">{{
            (obj_airSwitch.irms || 0 * 0.01).toFixed(2)
          }}</el-descriptions-item>
          <el-descriptions-item label="电压有效值/V">{{
            (obj_airSwitch.urms || 0 * 0.1).toFixed(1)
          }}</el-descriptions-item>
          <!-- <el-descriptions-item label="功率因数" v-if="obj_airSwitch.pf">{{
            (obj_airSwitch.pf * 0.001).toFixed(2)
          }}</el-descriptions-item> -->
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handlefinish(2, dev_detail)"
            >处理完成</el-button
          >
          <el-button type="primary" @click="handlePolice(2, dev_detail)"
            >开始处理</el-button
          ><el-button @click="dev_detailShow = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted ,getCurrentInstance} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { dictionaries, getoperator_list } from "../../assets/js/dictionaries";
import { download } from "../../assets/js/fileExport";
import parsing from "../../assets/js/parsing";
import { getAeaTreeList } from "../../assets/js/dictionaries";
import api from "../../api/api";
var projectId = Number(localStorage.getItem("projectId"));
export default {
  name: "basetable",
  components: {  },
  setup(props, context) {
    const router = useRouter();
    const route = useRoute();
    const query = reactive({
      value: "",
      name: "",
      pageNum: 1,
      pageSize: 10,
    });
    const defaultTime = [
      new Date(2000, 1, 1, 0, 0, 0),
      new Date(2000, 2, 1, 23, 59, 59),
    ];
    let { proxy } = getCurrentInstance();
    const alarmSet = reactive({
      name: "",
      region: "",
    });
    const shaving = reactive({
      id: "",
      projectId: null,
      operateDescb: "",
      img: [],
      remark: "",
    });
    const equipmt = ref([]);
    const isSearch = ref(context.attrs.isSearch);
    const ismodule = ref(context.attrs.ismodule);
    const searchfrom = reactive({
      queryProjectId: null,
      queryIsAlarming: 1,
      queryFloor: null,
      queryAlarmLevel: null,
      queryRoomNum: route.query.roomNum,
      queryAreaCode: route.query.areaCode,
      queryDeviceName: null,
      queryDevType: null,
      queryIsDisable: null,
      queryAlarmType: null,
      queryAlarmState: null,
      queryCheckState: null,
      queryImei: null,
      queryAlarmTimeStart: null,
      queryAlarmTimeEnd: null,
      queryStartHandleTime: null,
      queryEndHandleTime: null,
      queryAlarmNotifyOperator: null,
      queryAlarmMaintainer: null,
      pageNum: 1,
      pageSize: 10,
    });
    if (ismodule.value == 1) {
      searchfrom.pageSize = 5;
    }

    // 通用备注
    const remarkList = ref([]);
    dictionaries("DATANODE").then((res) => {
      equipmt.value = res;
    });
    // 实时报警查看
    const is_look_permission = ref(false);
    proxy.$permissionList("DEVICEALARM_R_VIEW").then((res) => {
      is_look_permission.value = res;
    });
    // 历史报警查看
    const is_look_HistoricalAlarm = ref(false);
    proxy.$permissionList("DEVICEALARM_L_VIEW").then((res) => {
      is_look_HistoricalAlarm.value = res;
    });
    // 报警设置查看
    const is_look_AlarmSet = ref(false);
    proxy.$permissionList("DEVICEALARM_SET_VIEW").then((res) => {
      is_look_AlarmSet.value = res;
    });
    // 已知报警操作
    const is_look_Knownpolice = ref(false);
    proxy.$permissionList("DEVICEALARM_KNOW_OPERATE").then((res) => {
      is_look_Knownpolice.value = res;
    });
    // 处理报警操作
    const is_look_dealpolice = ref(false);
    proxy.$permissionList("DEVICEALARM_HANDLE_OPERATE").then((res) => {
      is_look_dealpolice.value = res;
    }); // 导出报警操作
    const is_look_ExportAlarm = ref(false);
    proxy.$permissionList("DEVICEALARM_EXPORT").then((res) => {
      is_look_ExportAlarm.value = res;
    });
    //关闭报警操作
    const is_look_CloseAlarm = ref(false);
    proxy.$permissionList("DEVICEALARM_CLOSE_OPERATE").then((res) => {
      is_look_CloseAlarm.value = res;
    });
    //报警编辑操作
    const is_look_AlarmsetEdit = ref(false);
    proxy.$permissionList("DEVICEALARM_OPERATE").then((res) => {
      is_look_AlarmsetEdit.value = res;
    });
    //报警编辑操作
    const is_AlarmNotifyEdit = ref(false);
    proxy.$permissionList("DEVICEALARM_NOTIFY_OPERATE").then((res) => {
      is_AlarmNotifyEdit.value = res;
    });
    const is_AlarmNotify = ref(false);
    proxy.$permissionList("DEVICEALARM_NOTIFY_VIEW").then((res) => {
      is_AlarmNotify.value = res;
    });
    const personnelList = ref([]);
    getoperator_list().then((res) => {
      personnelList.value = res;
    });
    onMounted(() => {
      setTimeout(() => {
        projectId = Number(localStorage.getItem("projectId"));
        shaving.projectId = projectId;
        searchfrom.queryProjectId = projectId;
        console.log(projectId);
        getData();
      }, 500);
    });

    const searchAlarmSet = reactive({
      queryProjectId: projectId,
      queryDevType: null,
      queryAlarmType: null,
      queryAlarmLevel: null,
      queryIsDelay: null,
      querySendSms: null,
      queryIsCall: null,
      queryIsDisable: null,
    });
    const addAlarmSet = reactive({
      id: projectId,
      alarmShowNumber: null,
      alarmNotifyOperator: null,
      alarmMaintainer: null,
    });
    const initializeAreaCode = ref("");
    const tableData = ref([{
		alarmTypeName:"温度过高",
		alarmState:0,
	}]);
    const pageTotal = ref(0);
    const personnel = ref("");
    const maintainPersonnel = ref([]);
    const itemBuilding = ref("");
    const itemArea = ref("");
    const personnelInfo = ref([]);
    const dev_detailShow = ref(false);
    // 获取表格数据
    const getData = () => {
    //   api
    //     .postFormAPI("backup/alarmInfo/search", searchfrom)
    //     .then((res) => {
    //       if (res.data.code == 1) {
    //         tableData.value = res.data.data.list;
    //         pageTotal.value = res.data.data.total;
    //       } else {
    //         ElMessage.error(res.data.message);
    //       }
    //       //数据处理
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    };
    // getData();
    const parent_category = ref([]);
    proxy.$getAeaTreeList().then((res) => {
      parent_category.value = res;
    });
    // 查询操作
    const handleSearch = () => {
      query.queryAlarmType = Number(query.queryAlarmType);
      searchfrom.pageNum = 1;
      getData();
    };
    // 清空操作
    const emptySearch = () => {
      searchfrom.queryFloor = null;
      searchfrom.queryRoomNum = "";
      searchfrom.queryDeviceName = null;
      searchfrom.queryImei = null;
      searchfrom.queryAlarmType = null;
      searchfrom.queryAreaCode = null;
      searchfrom.queryDevType = null;
      searchfrom.queryAlarmState = "";
      searchfrom.queryCheckState = null;
      searchfrom.queryAlarmTimeStart = "";
      searchfrom.queryAlarmTimeEnd = "";
      searchfrom.queryStartHandleTime = "";
      searchfrom.queryEndHandleTime = "";
      searchfrom.queryAlarmLevel = null;
      searchfrom.queryIsDisable = null;
      searchfrom.queryAlarmNotifyOperator = null;
      searchfrom.queryAlarmMaintainer = null;
      searchfrom.pageNum = 1;
      queryBuildingAreaCode.value = null;
      alarm_time.value = "";
      dispose_time.value = "";
      searchAlarmSet.queryDevType = null;
      searchAlarmSet.queryAlarmType = null;
      searchAlarmSet.queryAlarmLevel = null;
      searchAlarmSet.queryIsDelay = null;
      searchAlarmSet.querySendSms = null;
      searchAlarmSet.queryIsCall = null;
      searchAlarmSet.queryIsDisable = null;
    };
    // 分页导航
    const handlePageChange = (val) => {
      searchfrom.pageNum = val;
      getData();
    };

    // 处理完成操作
    const disposeId = ref("");
    const finshVisible = ref(false);
    const uploadc = ref(null);
    const handlefinish = (indexid, row) => {
      if (indexid == 2) {
        personnelInfo.value = [
          {
            id: row.id,
            areaCode: row.areaCode,
          },
        ];
      }
      shaving.img = [];
      shaving.operateDescb = null;
      if (personnelInfo.value.length == 0) {
        ElMessage.error("请选择设备");
        return;
      }
      finshVisible.value = true;
      dictionaries("GeneralRemark").then((res) => {
        remarkList.value = res;
      });
      uploadc.value.clearFiles();
    };

    // 表格编辑时弹窗和保存
    const editVisible = ref(false);
    let form = reactive({
      name: "",
      address: "",
    });
    const dev_detail = ref({});
    const handledispose = (index, row) => {
      dev_detailShow.value = true;
      dev_detail.value = row;
      getAirswitch(row);
    };

    // 查看详情
    const handledetail = (index, row) => {
      var item = JSON.stringify(row);
      router.push("/alarm_detail?alarmId=" + row.id);
    };
    const HandlerSuccess = () => {
      shaving.remark = shaving.img.toString();
      for (var i = 0; i < personnelInfo.value.length; i++) {
        api
          .postFormAPI("backup/alarmInfo/handle", {
            id: personnelInfo.value[i].id,
            projectId: shaving.projectId,
            img: shaving.img,
            remark: shaving.remark,
            operateDescb: shaving.operateDescb,
          })
          .then((res) => {
            if (res.data.code == 1) {
              if (personnelInfo.value.length == i) {
                finshVisible.value = false;
                dev_detailShow.value = false;
                ElMessage.success("操作成功");
                getData();
                personnelInfo.value = [];
              }
            } else {
              ElMessage.error(res.data.message);
            }
            //数据处理
          })
          .catch((err) => {
            console.log(err);
          });
      }
    };
    const changeAlarm_time = (row) => {
      if (row) {
        searchfrom.queryAlarmTimeStart = row[0];
        searchfrom.queryAlarmTimeEnd = row[1];
      } else {
        searchfrom.queryAlarmTimeStart = null;
        searchfrom.queryAlarmTimeEnd = null;
      }
    };
    const handleChange = (row) => {
      if (row) {
        searchfrom.queryStartHandleTime = row[0];
        searchfrom.queryEndHandleTime = row[1];
      } else {
        searchfrom.queryStartHandleTime = null;
        searchfrom.queryEndHandleTime = null;
      }
    };
    const alarm_time = ref("");
    const dispose_time = ref("");
    const queryBuildingAreaCode = ref("");
    const handleChangeAreaCode = (res) => {
      // if (res && res.length > 1) {
      //   var index = res.length - 1;
      // }
      searchfrom.queryAreaCode = res[0];
    };
    const saveEditDispose = () => {
      for (var i = 0; i < personnelInfo.value.length; i++) {
        api
          .postFormAPI("backup/alarmInfo/notice", {
            id: personnelInfo.value[i].id,
            noticeOperator: personnel.value,
            projectId: projectId,
          })
          .then((res) => {
            if (res.data.code == 1) {
              if (personnelInfo.value.length == i) {
                ElMessage.success("已知该报警信息");
                editVisible.value = false;
                dev_detailShow.value = false;
                getData();
                personnelInfo.value = [];
                // setTimeout(function () {
                //   router.go(0);
                // }, 500);
              }
            } else {
              ElMessage.error(res.data.message);
            }
            //数据处理
          })
          .catch((err) => {});
      }
    };
    const remarkValue = ref("");
    const remark_input = ref();
    // 获取校区
    const campusList = ref([]);
    proxy.$branchOfficeTree().then((res) => {
      campusList.value = res;
    });
    // 获取楼栋
    const handleAreaCode = (res) => {
      var index = "";
      parent_category.value = [];
      searchfrom.queryFloor = null;
      if (res && res.length > 1) {
        index = res.length - 1;
        searchfrom.queryAreaCode = res[index];
      }
      proxy.$listExist(res[index]).then((res) => {
        parent_category.value = res;
      });
    };
    const getAlarmNotifyData = () => {
      api
        .postFormAPI("backup/alarmNotify/search", searchfrom)
        .then((res) => {
          if (res.data.code == 1) {
            tableData.value = res.data.data;
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {
          console.log(err);
        });
    };
    const AlarmLevel = ref([]);

    const loading = ref(false);
    const handleClick = (e) => {
      // 报警设置
      console.log(e.index);
      if (e.index == 2) {
        loading.value = true;
        getprojectSet();
        searchData();
      } else if (e.index == 0 || e.index == 1) {
        searchfrom.queryIsAlarming = e.index == 0 ? 1 : 0;
        getData();
      } else if (e.index == 3) {
        searchfrom.queryIsAlarming = e.index == 0 ? 1 : 0;
        getAlarmNotifyData();
      }
      // emptySearch();
      searchfrom.queryCheckState = null;
      searchfrom.queryAlarmState = null;
      searchfrom.pageSize = 10;
      searchfrom.pageNum = 1;
      personnelInfo.value = [];
    };
    dictionaries("AlarmLevel").then((res) => {
      AlarmLevel.value = res;
    });
    const getprojectSet = () => {
      api
        .getListAPI(
          "backup/alarmSet/projectSet?projectId=" + addAlarmSet.id,
          {}
        )
        .then((res) => {
          if (res.data.code == 1) {
            addAlarmSet.alarmShowNumber = res.data.data.alarmShowNumber;
            addAlarmSet.alarmNotifyOperator = res.data.data.alarmNotifyOperator;
            addAlarmSet.alarmMaintainer = res.data.data.alarmMaintainer;
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {
          console.log(err);
        });
    };
    const devTypeList = ref([]);
    const is_AlarmStype = ref(true);
    const AlarmTypeList = ref([]);
    const tableDataAlarm = ref([]);
    const getDevType = () => {
      api
        .getListAPI("backup/alarmSet/devType", {})
        .then((res) => {
          if (res.data.code == 1) {
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].checked = false;
            }
            devTypeList.value = res.data.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    getDevType();
    const handlequeryDevType = () => {
      is_AlarmStype.value = false;
      getalarmType();
    };
    const getalarmType = () => {
      var queryDevType = searchAlarmSet.queryDevType || searchfrom.queryDevType;
      api
        .getListAPI("backup/alarmSet/alarmType?devType=" + queryDevType, {})
        .then((res) => {
          if (res.data.code == 1) {
            AlarmTypeList.value = res.data.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    const searchData = () => {
      api
        .postFormAPI("backup/alarmSet/search", searchAlarmSet)
        .then((res) => {
          if (res.data.code == 1) {
            loading.value = false;
            for (var i = 0; i < res.data.data.length; i++) {
              res.data.data[i].is_delayTime =
                res.data.data[i].confirmSecond == 0 ? 0 : 1;
              res.data.data[i].alarmLevel = String(res.data.data[i].alarmLevel);
            }
            tableDataAlarm.value = res.data.data;
            getSpanArr(res.data.data);
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {
          console.log(err);
        });
    };
    //延迟报警
    const dev_Initializing = ref(false);
    const obj_dev = ref({});
    var DelayTime = null;
    const handledevInitializing = () => {
      dev_Initializing.value = true;
      for (var i = 0; i < tableDataAlarm.value.length; i++) {
        for (var j = 0; j < devTypeList.value.length; j++) {
          if (
            tableDataAlarm.value[i].devType == devTypeList.value[j].devTypeId
          ) {
            devTypeList.value[j].checked = true;
            dev_list.value.push(devTypeList.value[j].devTypeId);
          }
        }
      }
      // console.log(devTypeList.value)
      // console.log(tableDataAlarm.value)
    };
    const handleinputDelayTime = (e, row) => {
      if (e) {
        DelayTime = Number(e);
      } else {
        DelayTime = null;
      }
      obj_dev.value = row;
    };
    // 鼠标移除
    const handleBlurDelayTime = (e) => {
      if (!DelayTime) {
        // ElMessage.error("请编辑延迟时间");
        return;
      }
      if (obj_dev.value) {
        update_alarmSet(obj_dev.value);
      }
    };
    // 推送延迟通知
    const handleBlurPutDelayTime = (row) => {
      obj_dev.value = row;
      if (DelayTime == null) {
        ElMessage.error("请编辑延迟时间");
        return;
      }
      if (obj_dev.value) {
        update_alarmSet(obj_dev.value);
      }
    };
    // 是否实时报警
    const changeRadio = (e, index) => {
      if (e == 0) {
        tableDataAlarm.value[index].confirmSecond = 0;
        tableDataAlarm.value[index].is_delayTime = 0;
      } else {
        tableDataAlarm.value[index].confirmSecond = 1800;
        tableDataAlarm.value[index].is_delayTime = 1;
      }
      update_alarmSet(tableDataAlarm.value[index]);
    };
    // 是否发送短信
    const handleSmsReminder = (e, row) => {
      row.sendSms = e;
      if (row.id) {
        update_alarmSet(row);
      }
    };
    // 是否语音通知
    const handleVoicePrompt = (e, row) => {
      row.isCall = e;
      if (row.id) {
        update_alarmSet(row);
      }
    };
    // 是否屏蔽报警
    const handleShieldingAlarm = (e, row) => {
      row.isDisable = e;
      if (row.id) {
        update_alarmSet(row);
      }
    };
    // 更新报警设置
    const update_alarmSet = (obj) => {
      api
        .postFormAPI("backup/alarmSet/update", obj)
        .then((res) => {
          if (res.data.code == 1) {
            // ElMessage.success("保存成功");
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {
          console.log(err);
        });
    };
    const onSubmit = () => {
      if (!addAlarmSet.alarmShowNumber) {
        ElMessage.error("请输入报警类型数量");
        return;
      } else if (!addAlarmSet.alarmNotifyOperator) {
        ElMessage.error("请选择报警信息平台接收对象");
        return;
      } else if (!addAlarmSet.alarmMaintainer) {
        ElMessage.error("请选择维修信息接收对象");
        return;
      }
      ElMessageBox.confirm("确定保存设置？", {
        type: "warning",
      }).then((res) => {
        if (res == "confirm") {
          api
            .postFormAPI("backup/alarmSet/updateProjectSet", addAlarmSet)
            .then((res) => {
              if (res.data.code == 1) {
                ElMessage.success("设置成功");
              } else {
                ElMessage.error(res.data.message);
              }
              //数据处理
            })
            .catch((err) => {});
        }
      });
    };

    //初始化设备类型
    const handleSaveDevInitializing = () => {
      dev_list.value = parsing.array_deduplication(dev_list.value);
      api
        .postFormAPI("backup/alarmSet/init", {
          projectId: searchAlarmSet.queryProjectId,
          devTypeList: dev_list.value,
        })
        .then((res) => {
          if (res.data.code == 1) {
            ElMessage.success("初始化成功");
            dev_Initializing.value = false;
            searchData();
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {});
    };
    //选中的设备
    const dev_list = ref([]);
    const changedev = (event, item) => {
      if (event == true) {
        dev_list.value.push(item.devTypeId);
      } else {
        for (var i = 0; i < dev_list.value.length; i++) {
          if (dev_list.value[i] == item.devTypeId) {
            dev_list.value.splice(i, 1);
          }
        }
      }
    };
    // 导出历史报警
    const handleExport = () => {
      api
        .postFormAPI("backup/alarmInfo/exportExcel", searchfrom)
        .then((res) => {
          if (res.data.code == 1) {
            getdownload(res.data.data);
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {});
    };
    const getdownload = (code) => {
      proxy
        .$axios({
          method: "GET",
          url: api.getUrl() + "backup/excel/download?code=" + code,
          responseType: "blob",
        })
        .then((resdata) => {
          download(resdata.data, "历史报警.xlsx");
        })
        .catch((err) => {
          if (!handleError(err.response)) {
            error(err);
          }
        });
    };
    // 图片上传
    const imgList = ref([]);
    const uploadFile = (item) => {
      imgList.value.push(item);
      const form1 = new FormData();
      var token = localStorage.getItem("token");
      form1.append("file", item.file);
      proxy
        .$axios({
          method: "post",
          url: api.getUrl() + "auth/account/uploadFile",
          data: form1,
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: "Bearer " + token,
          },
        })
        .then((resdata) => {
          shaving.img.push(resdata.data.data);
        })
        .catch((err) => {});
    };
    const beforeremoveElse = (file, fileList) => {
      imgList.value = fileList;
    };
    const noticeId = ref("");
    const handlePolice = (index, row) => {
      if (index == 2) {
        personnelInfo.value = [
          {
            id: row.id,
            noticeOperator: row.alarmMaintainer,
          },
        ];
      }
      if (personnelInfo.value.length == 0) {
        ElMessage.error("请选择设备");
        return;
      }
      editVisible.value = true;
    };
    const handleAlarmLevel = (event, row) => {
      row.alarmLevel = event;
      update_alarmSet(row);
    };
    const dialogVisible = ref(false);
    const previewUrl = ref("");
    const handlePictureCardPreview = (file) => {
      dialogVisible.value = true;
      previewUrl.value = file.url;
    };
    const handleclose = (row) => {
      dialogVisible.value = row;
      editVisible.value = false;
      finshVisible.value = false;
      personnelInfo.value = [];
      searchData();
    };
    const spanArr = ref([]);
    const pos = ref(0);
    const getSpanArr = (data) => {
      spanArr.value = [];
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          spanArr.value.push(1);
          pos.value = 0;
        } else {
          // 判断当前元素与上一个元素是否相同  inAccessCode（批次字段）
          if (data[i].devType == data[i - 1].devType) {
            spanArr.value[pos.value] += 1;
            spanArr.value.push(0);
          } else {
            spanArr.value.push(1);
            pos.value = i;
          }
        }
      }
    };
    const objectSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
      if (columnIndex === 0) {
        const _row = spanArr.value[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
      // if (columnIndex === 0) {
      //   if (rowIndex % 2 === 0) {
      //     return {
      //       rowspan: row.devType,
      //       colspan: 1,
      //     };
      //   } else {
      //     return {
      //       rowspan: 0,
      //       colspan: 0,
      //     };
      //   }
      // }
    };
    const handleSelectionChange = (selection, row) => {
      personnelInfo.value = [];
      for (var i = 0; i < selection.length; i++) {
        // checkState 2已处理 1处理中
        if (selection[i].checkState != 2 && selection[i].checkState != 1) {
          personnelInfo.value.push(selection[i]);
        }
        if (selection[i].checkState == 2) {
          ElMessage.error("已处理不再处理");
          return;
        } else if (selection[i].checkState == 2) {
          ElMessage.error("处理中设备不再处理");
          return;
        }
      }
    };
    const selectAllchange = (row) => {
      personnelInfo.value = [];
      for (var i = 0; i < row.length; i++) {
        // checkState 2已处理 1处理中
        if (row[i].checkState != 2 && row[i].checkState != 1) {
          personnelInfo.value.push(row[i]);
        }
        if (row[i].checkState == 2) {
          ElMessage.error("已处理不再处理");
          return;
        } else if (row[i].checkState == 1) {
          ElMessage.error("处理中设备不再处理");
          return;
        }
      }
    };
    const isBatchNotifSet = ref(0);
    const notifySetbatch = ref(null);
    const handlePoliceNotifSet = (index, row) => {
      // index等于1 批量报警通知设置  ，index等于2 修改报警通知设置  ，index等于3 初始化通知设置

      notifySetbatch.value = index;
      if (index == 2) {
        maintainPersonnel.value = [];
        personnel.value = [];
        personnelInfo.value = [
          {
            id: row.id,
            noticeOperator: row.alarmMaintainer,
            areaCode: row.areaCode,
          },
        ];
        for (var i = 0; i < row.alarmMaintainerInfo.length; i++) {
          maintainPersonnel.value.push(row.alarmMaintainerInfo[i].id);
        }
        for (var i = 0; i < row.alarmNotifyOperatorInfo.length; i++) {
          personnel.value.push(row.alarmNotifyOperatorInfo[i].id);
        }
        itemBuilding.value = row.building || "";
        itemArea.value = row.office || "" + "-" + row.branchOffice || "";
        isBatchNotifSet.value = 1;
      } else {
        isBatchNotifSet.value = 0;
        personnel.value = null;
        maintainPersonnel.value = null;
      }
      if (personnelInfo.value.length == 0) {
        ElMessage.error("请选择");
        return;
      }
      editVisible.value = true;
    };
    const buildList = ref([]);
    const handleinitializeNotifySet = () => {
      // index等于1 批量报警通知设置  ，index等于2 修改报警通知设置  ，index等于3 初始化通知设置

      personnel.value = null;
      maintainPersonnel.value = null;
      getAeaTreeList(projectId).then((res) => {
        buildList.value = res;
        notifySetbatch.value = 3;
        // isBatchNotifSet  index等于1 批量报警通知设置   index等于2 初始化通知设置
        isBatchNotifSet.value = 2;
        editVisible.value = true;
      });
    };
    const handleInitializeAreaCode = (arr) => {
      initializeAreaCode.value = arr[arr.length - 1];
    };
    const is_epTotal = ref(null);
    const obj_airSwitch = ref({});
    const getAirswitch = (row) => {
      console.log(row);
      api
        .getListAPI(
          "backup/deviceData/zlinkDeviceInfo?imei=" +
            row.imei +
            "&lineId=" +
            row.shunt,
          {}
        )
        .then((res) => {
          if (res.data.code == 1) {
            // if (res.data.data.epTotal) {
            is_epTotal.value = res.data.data.epTotal;
            obj_airSwitch.value = res.data.data;
            // }
          } else {
            ElMessage.error(res.data.message);
          }
          //数据处理
        })
        .catch((err) => {});
    };

    return {
      noticeId,
      spanArr,
      pos,
      isSearch,
      defaultTime,
      dialogVisible,
      previewUrl,
      is_look_permission,
      is_look_HistoricalAlarm,
      is_look_AlarmSet,
      is_AlarmNotify,
      is_AlarmNotifyEdit,
      is_look_Knownpolice,
      is_look_dealpolice,
      is_look_ExportAlarm,
      is_look_CloseAlarm,
      is_look_AlarmsetEdit,
      ismodule,
      buildList,
      shaving,
      uploadc,
      query,
      imgList,
      tableData,
      pageTotal,
      editVisible,
      finshVisible,
      form,
      remarkList,
      searchfrom,
      remarkValue,
      remark_input,
      parent_category,
      queryBuildingAreaCode,
      initializeAreaCode,
      alarmSet,
      proxy,
      searchAlarmSet,
      devTypeList,
      is_AlarmStype,
      AlarmTypeList,
      AlarmLevel,
      tableDataAlarm,
      equipmt,
      alarm_time,
      dispose_time,
      personnelInfo,
      addAlarmSet,
      dev_Initializing,
      obj_dev,
      loading,
      personnel,
      maintainPersonnel,
      itemBuilding,
      itemArea,
      campusList,
      personnelList,
      isBatchNotifSet,
      notifySetbatch,
      dev_detailShow,
      dev_detail,
      is_epTotal,
      obj_airSwitch,
      alarmstateList: [
        {
          value: 1,
          label: "报警中",
        },
        {
          value: 0,
          label: "已恢复",
        },
      ],
      his_alarmstateList: [
        {
          value: 1,
          label: "报警中",
        },
        {
          value: 2,
          label: "已恢复",
        },
      ],
      alarmdisposeList: [
        {
          value: 0,
          label: "待处理",
        },
        {
          value: 1,
          label: "处理中",
        },
      ],
      alarmdisposeList1: [
        {
          value: 1,
          label: "处理中",
        },
        {
          value: 2,
          label: "已处理",
        },
      ],
      alarmstate: [
        {
          value: 1,
          label: "是",
        },
        {
          value: 0,
          label: "否",
        },
      ],
      handleInitializeAreaCode,
      handleSelectionChange,
      selectAllchange,
      handleclose,
      handlePictureCardPreview,
      handleAlarmLevel,
      handlePolice,
      handleExport,
      handleSmsReminder,
      handleVoicePrompt,
      handleShieldingAlarm,
      changeRadio,
      handleinputDelayTime,
      handleBlurPutDelayTime,
      handleBlurDelayTime,
      changedev,
      handleSaveDevInitializing,
      handledevInitializing,
      onSubmit,
      handleClick,
      handlePoliceNotifSet,
      handleinitializeNotifySet,
      handlequeryDevType,
      handleSearch,
      handlePageChange,
      handlefinish,
      handledispose,
      handledetail,
      HandlerSuccess,
      saveEditDispose,
      emptySearch,
      changeAlarm_time,
      handleChange,
      handleChangeAreaCode,
      handleAreaCode,
      objectSpanMethod,
      uploadFile,
      beforeremoveElse,
    };
  },
};
</script>

<style scoped>
@import "../../assets/css/common.css";
.container {
  padding-bottom: 40px;
}
.devTypeName {
  width: 100%;
  display: flex;
  flex-direction: wrap;
  flex-wrap: wrap;
}
.devTypeName .el-form-item {
  width: 480px;
}
/* .el-checkbox__label {
  width: 80%;
  word-wrap: break-word;
} */
.colorblur {
  color: #409eff;
}
.handle-input1 {
  width: 50%;
}
</style>
